const axios = require('axios');

const BASE_URL = 'http://localhost:3000/api';
let authToken = '';

// 测试用户数据
const testUser = {
  username: 'testuser',
  email: 'test@example.com',
  password: 'Password123'
};

// 测试注册
async function testRegister() {
  try {
    console.log('🔐 测试用户注册...');
    const response = await axios.post(`${BASE_URL}/auth/register`, testUser);
    console.log('✅ 注册成功:', response.data.message);
    authToken = response.data.data.token;
    return true;
  } catch (error) {
    if (error.response && error.response.status === 400) {
      console.log('⚠️ 用户已存在，跳过注册');
      return true;
    }
    console.error('❌ 注册失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试登录
async function testLogin() {
  try {
    console.log('🔑 测试用户登录...');
    const response = await axios.post(`${BASE_URL}/auth/login`, {
      username: testUser.username,
      password: testUser.password
    });
    console.log('✅ 登录成功:', response.data.message);
    authToken = response.data.data.token;
    return true;
  } catch (error) {
    console.error('❌ 登录失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试获取用户信息
async function testGetUserInfo() {
  try {
    console.log('👤 测试获取用户信息...');
    const response = await axios.get(`${BASE_URL}/auth/me`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    console.log('✅ 获取用户信息成功:', response.data.data);
    return true;
  } catch (error) {
    console.error('❌ 获取用户信息失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试健康检查
async function testHealth() {
  try {
    console.log('🏥 测试健康检查...');
    const response = await axios.get('http://localhost:3000/health');
    console.log('✅ 健康检查成功:', response.data.message);
    return true;
  } catch (error) {
    console.error('❌ 健康检查失败:', error.response?.data || error.message);
    return false;
  }
}

// 运行所有测试
async function runTests() {
  console.log('🚀 开始API测试...\n');
  
  const tests = [
    { name: '健康检查', fn: testHealth },
    { name: '用户注册', fn: testRegister },
    { name: '用户登录', fn: testLogin },
    { name: '获取用户信息', fn: testGetUserInfo }
  ];
  
  let passed = 0;
  let total = tests.length;
  
  for (const test of tests) {
    console.log(`\n📋 测试: ${test.name}`);
    const success = await test.fn();
    if (success) passed++;
    console.log('─'.repeat(50));
  }
  
  console.log(`\n📊 测试结果: ${passed}/${total} 通过`);
  if (passed === total) {
    console.log('🎉 所有测试通过！');
  } else {
    console.log('⚠️ 部分测试失败，请检查服务器状态');
  }
}

// 如果直接运行此文件
if (require.main === module) {
  runTests().catch(console.error);
}

module.exports = {
  testRegister,
  testLogin,
  testGetUserInfo,
  testHealth,
  runTests
}; 